package com.conferenceroom.controller;


import com.conferenceroom.dto.AjaxResult;
import com.conferenceroom.entity.User;
import com.conferenceroom.mapper.UserMapper;
import com.conferenceroom.service.ILoginService;
import com.conferenceroom.util.IdentityType;
import com.conferenceroom.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin // 允许前端访问
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginAndRegisterController {

    @Autowired
    private ILoginService loginService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private UserMapper userMapper;
    @PostMapping
    public AjaxResult login(@RequestBody User user) {
        User login = loginService.doLogin(user);
        if (login != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("user_id", login.getUserId());
            map.put("username", login.getUsername());
            switch (login.getUserType()) {
                case 0:
                    map.put("identity", IdentityType.USER);
                    break;
                case 1:
                    map.put("identity", IdentityType.EMPLOYEE);
                    break;
                case 2:
                    map.put("identity", IdentityType.ADMIN);
                    break;
                default:
                    // 处理未知的identity类型
                    throw new IllegalArgumentException("Unknown identity type!");
            }
            String token = jwtUtil.generateToken(map);
            AjaxResult result = AjaxResult.success(map);
            result.put("token", token);
            return result;
        }
        List<User> users = userMapper.selectByUsername(user.getUsername());
        if (!users.isEmpty() && users.get(0).getStatus() == 2) {
            return AjaxResult.fail("账号正在审核中，请等待审核通过");
        }
        if (!users.isEmpty() && users.get(0).getStatus() == 0) {
            return AjaxResult.fail("账号已被冻结，请联系管理员");
        }
        return AjaxResult.fail("用户名或密码错误");
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody User user) {
        String flag = loginService.doRegister(user);
        if (flag.endsWith("审核")) {
            return AjaxResult.success("注册提交:"+flag);
        }
        return AjaxResult.fail("注册提交失败:"+flag);
    }
}
